package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeNameExistException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.result.PageResult;
import com.sky.service.admin.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO 员工数据
     * @return 插入结果
     */
    @Override

    public Integer addEmployee(EmployeeDTO employeeDTO) {

        //判断用户名是否已存在
        String username = employeeDTO.getUsername();
        Employee byUsername = employeeMapper.getByUsername(username);
        if (byUsername != null) {
            //用户名已存在
            throw new EmployeeNameExistException(byUsername.getName() + "已存在");
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置默认密码123456 MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置账号状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置创建时间
        // employee.setCreateTime(LocalDateTime.now());
        //设置更新时间
        // employee.setUpdateTime(LocalDateTime.now());
        /*
         * BaseContext 内部new了一个ThreadLocal，进行传递参数
         * 线程隔离，每个线程的BaseContext对象是隔离的
         *ThreadLocal：用于同一线程内的变量共享
         * */
        //设置创建人
        // employee.setCreateUser(BaseContext.getCurrentId());
        log.warn("创建人的id：{}", BaseContext.getCurrentId());
        //设置修改人
        // employee.setUpdateUser(BaseContext.getCurrentId());
        Integer result = employeeMapper.addEmployee(employee);
        return result;
    }

    @Override
    public PageResult pageQuery(
            @Param("name") String name, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Employee> list = employeeMapper.pageQuery(name, page, pageSize);
        Page<Employee> employeePage = (Page<Employee>) list;
        log.info("员工分页查询结果：{}", employeePage);
        PageResult pageResult = new PageResult(employeePage.getTotal(), employeePage.getResult());
        log.info("员工分页查询结果：{}", pageResult);

        return pageResult;
    }

    @Override
    public Integer startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status == StatusConstant.DISABLE ? StatusConstant.DISABLE : StatusConstant.ENABLE)
                .id(id)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        Integer result = employeeMapper.updateStartOrStop(employee);
        log.info("员工状态：{}", status);
        return result;
    }

    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return employee;
    }

    @Override
    @AutoFill
    public Integer updateEmpInfo(Employee employee) {
        //employee.setUpdateTime(LocalDateTime.now());
        Integer result = employeeMapper.updateEmpInfo(employee);
        return result;
    }


}
